package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.util.jwt.AESUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.MemberConverter;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.AddressListRequest;
import com.cskaoyan.user.dto.UserCheckResponse;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.service.ILoginService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date 2022-12-03 11:38
 * @Created by yepq2025@outlook.com
 */
@Service
public class ILoginServiceImpl implements ILoginService {
    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    MemberConverter memberConverter;

    @Override
    public Map<String, Object> verifyLogin(String token) {
        // 对Token进行解析和数据封装返回
        String freeJwt = JwtTokenUtils.builder ( ).token ( token ).build ( ).freeJwt ( );
        HashMap<String, Object> map = new HashMap<> ( );
        Gson gson = new Gson ( );
        HashMap tokenMap = gson.fromJson ( freeJwt, map.getClass ( ) );
        return tokenMap;
    }

    /**
     * 实现用户登录功能
     *
     * @param request
     */
    /**
     * TODO: 实现登录功能接口
     * author: yepq2025@outlook.com
     * time: 2022-12-03 11:40:39
     * @param request
     */
    @Override
    public UserLoginResponse login(UserRegisterRequest request) {
        UserLoginResponse response = new UserLoginResponse ( );
        try {
            // 1、对参数校验
            request.requestCheck ();
            Member member = memberConverter.UserLoginRequestToMember ( request );

            // 2、向数据库查询用户的账号、密码是否正确
            Example example = new Example ( Member.class );
            String password = member.getPassword ( );
            // 2.1 对密码进行加密后查询
            AESUtil aesUtil = new AESUtil ( password );
            String encrypt = aesUtil.encrypt ( );
            example.createCriteria ().andEqualTo ( "username", member.getUsername () )
                                     .andEqualTo ( "password", encrypt );
            List<Member> members = memberMapper.selectByExample ( example );
            if (members.size () != 1) {
                response.setCode ( UserRetCode.USERORPASSWORD_ERRROR.getCode () );
                response.setMsg ( UserRetCode.USERORPASSWORD_ERRROR.getMessage () );
                return response;
            }
            // 3、判断成员是否激活
            String userName = request.getUserName ( );
            Example example1 = new Example ( Member.class );
            example1.createCriteria ().andEqualTo ( "username", member.getUsername () );
            List<UserVerify> userVerifies = userVerifyMapper.selectByExample ( example1 );
            for (UserVerify userVerify : userVerifies) {
                if ("N".equals ( userVerify.getIsVerify () )) {
                    response.setCode ( UserRetCode.USER_ISVERFIED_ERROR.getCode () );
                    response.setMsg ( UserRetCode.USER_ISVERFIED_ERROR.getMessage () );
                    return response;
                }
            }
            // 4、登录成功
            Member member1 = members.get ( 0 );
            response = memberConverter.userLoginResponseTOMember ( member1 );
            response.setCode ( UserRetCode.SUCCESS.getCode () );
            response.setMsg ( UserRetCode.SUCCESS.getMessage () );
        } catch (Exception e) {
            e.printStackTrace ();
            ExceptionProcessorUtils.wrapperHandlerException ( response, e );
        }
        return response;
    }


    /**
     * TODO: 登录验证
     * author: yepq2025@outlook.com
     * time: 2022-12-03 13:39:15
    */
    @Override
    public UserCheckResponse check(AddressListRequest request) {
        UserCheckResponse response = new UserCheckResponse ( );
        try {
            // 先进行参数校验
            request.requestCheck ();
            // 获取时间戳
            long l = System.currentTimeMillis ( );
            String time = l + "";
            String filename = "https://gper.club/server-img/avatars/000/00/00/user_origin_30.jpg?" + time;
            response.setFile ( filename );
            // 获取uid
            Long userId = request.getUserId ( );
            response.setUid ( userId );
            response.setFile ( filename );
            response.setCode ( UserRetCode.SUCCESS.getCode () );
            response.setMsg ( UserRetCode.SUCCESS.getMessage () );
        } catch (Exception e) {
            e.printStackTrace ();
            ExceptionProcessorUtils.wrapperHandlerException ( response, e );
        }

        return response;
    }
}
